package com.heatingcharge.service.unit.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heatingcharge.common.exception.BaseException;
import com.heatingcharge.common.util.BeanValidator;
import com.heatingcharge.common.util.LevelUtil;
import com.heatingcharge.common.util.ResponseCodeEnum;
import com.heatingcharge.dto.HeatChangeStationDTO;
import com.heatingcharge.entity.unit.HeatChangeStation;
import com.heatingcharge.entity.unit.HeatCompany;
import com.heatingcharge.entity.unit.ResBuilding;
import com.heatingcharge.mapper.unit.HeatChangeStationMapper;
import com.heatingcharge.mapper.unit.HeatCompanyMapper;
import com.heatingcharge.mapper.unit.ResBuildingMapper;
import com.heatingcharge.param.HeatChangeStationParam;
import com.heatingcharge.service.unit.IHeatChangeStationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 换热站  服务实现类
 * </p>
 *
 * @author devin.jiang
 * @since 2019-07-12
 */
@Service
public class HeatChangeStationServiceImpl extends ServiceImpl<HeatChangeStationMapper, HeatChangeStation> implements IHeatChangeStationService {

    @Autowired
    HeatCompanyMapper heatCompanyMapper;
    @Autowired
    ResBuildingMapper buillingMapper;
    @Override
    public IPage<HeatChangeStation> selectHeatChangeStationPage(Page heatChangeStationPage, HeatChangeStationDTO heatChangeStationDTO) {
        if (heatChangeStationDTO.getCompanyId()!=0){
            HeatCompany heatCompany = heatCompanyMapper.selectById(heatChangeStationDTO.getCompanyId());
            String level= LevelUtil.calculateLevel(heatCompany.getLevel(), heatCompany.getId());
            List<Integer> companyIds= heatCompanyMapper.selectList(
                    Wrappers.<HeatCompany>query().lambda().likeRight(HeatCompany::getLevel, level))
                    .stream().map(HeatCompany::getId).collect(Collectors.toList());
            companyIds.add(heatCompany.getId());
            heatChangeStationDTO.setCompanyList(companyIds);
        }

        return baseMapper.selectHeatChangeStationVo(heatChangeStationPage,heatChangeStationDTO);
    }

    @Override
    public boolean save(HeatChangeStationParam heatChangeStationParam) {
        //校验字段合法性
        BeanValidator.check(heatChangeStationParam);
        //检验换热站是否已经存在
        if (checkExist(heatChangeStationParam.getPlantId(),heatChangeStationParam.getName(),null)){
            //换热站已经存在
            throw new BaseException(ResponseCodeEnum.HEATCHANGESTATION_EXIST.getMessage(),ResponseCodeEnum.HEATCHANGESTATION_EXIST.getCode());
        }
        HeatChangeStation heatChangeStation=HeatChangeStation.builder()
                .name(heatChangeStationParam.getName())
                .plantId(heatChangeStationParam.getPlantId())
                .addr(heatChangeStationParam.getAddr())
                .build();
        return baseMapper.insert(heatChangeStation)>0;
    }
    /**
     * 同一热源厂下是否存在相同的换热站
     * @param plantId
     * @param name
     * @param id
     * @return
     */
    private boolean checkExist(Integer plantId,String name, Integer id) {
        QueryWrapper<HeatChangeStation> queryWrapper=new QueryWrapper<>();
        if (plantId!=null) {
            queryWrapper.eq("plant_id",plantId);
        }
        queryWrapper.eq("name",name);
        if (id!=null){
            queryWrapper.ne("id",id);
        }
        return this.list(queryWrapper).size()>0;
    }
    @Override
    public boolean update(HeatChangeStationParam heatChangeStationParam) {
        //校验字段合法性
        BeanValidator.check(heatChangeStationParam);
        //检验换热站是否已经存在
        if (checkExist(heatChangeStationParam.getPlantId(),heatChangeStationParam.getName(),heatChangeStationParam.getId())){
            //换热站已经存在
            throw new BaseException(ResponseCodeEnum.HEATCHANGESTATION_EXIST.getMessage(),ResponseCodeEnum.HEATCHANGESTATION_EXIST.getCode());
        }
        HeatChangeStation before=this.getById(heatChangeStationParam.getId());
        if (ObjectUtil.isNull(before)){
            throw new BaseException(ResponseCodeEnum.HEATCHANGESTATION_NON_EXIST.getMessage(),ResponseCodeEnum.HEATCHANGESTATION_NON_EXIST.getCode());
        }
        HeatChangeStation after=new HeatChangeStation();
        BeanUtils.copyProperties(heatChangeStationParam, after);

        return baseMapper.updateById(after)>0;
    }
    //删除
    @Override
    public boolean removeById(Serializable id) {
        // 换热站层级删除
        List<Integer> idList = buillingMapper.selectList(Wrappers.<ResBuilding>query().lambda().eq(ResBuilding::getStationId, id)).stream().map(ResBuilding::getId).collect(Collectors.toList());
        //如果存在子换热站  则不能删除
        if (idList.size()>0){
            throw new BaseException(ResponseCodeEnum.HEATCHANGESTATION_HAS_CHILDREN.getMessage(),ResponseCodeEnum.HEATCHANGESTATION_HAS_CHILDREN.getCode());
        }
        return super.removeById(id);
    }
}
